package cn.edu.seu.cose.qol.model.dao.config;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesWriter {
	
	private static final Map<String, PropertiesWriter> WRITER_POOL;
	static {
		WRITER_POOL = new HashMap<String, PropertiesWriter>();
	}
	
	private String _identifier;
	
	private Properties _properties;
	
	private OutputStream _out;
	
	public static synchronized PropertiesWriter getInstance(String filePath) throws IOException {
		if (WRITER_POOL.containsKey(filePath)) {
			return WRITER_POOL.get(filePath);
		}
		
		PropertiesWriter newInstance = new PropertiesWriter(filePath);
		WRITER_POOL.put(filePath, newInstance);
		return newInstance;
	}
	
	protected PropertiesWriter(String filePath) throws IOException {
		_identifier = filePath;
		
		createIfDoNotExist(filePath);
		
		_out = new BufferedOutputStream(new FileOutputStream(filePath));
		_properties = new Properties();
	}
	
	@Override
	protected void finalize() {
		WRITER_POOL.remove(_identifier);
	}
	
	public void setProperty(String key, String value) throws IOException {
		_properties.setProperty(key, value);
		_properties.store(_out, "set");
	}
	
	private void createIfDoNotExist(String filePath) {
		File propertiesFile = new File(filePath);
		
		if (!propertiesFile.exists()) {
			propertiesFile.mkdir();
		}
	}

}
